﻿using Book.Data;
using Book.Entities;
using Book.IRepositories;
using Book.JWT;
using Book.Models.UserWai;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace Book.Repositiories
{
    public class UserRepository : IUserRepository
    {
        private readonly BookDbContext _DbContext;
        private readonly IJwtService _jwt;

        public UserRepository(BookDbContext bookDbContext, IJwtService jwt)
        {
            this._DbContext = bookDbContext;
            this._jwt = jwt;
        }
     



        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="userWai"></param>
        public void AddUser(UserWai userWai)
        {
            //var md5Password = EncryptHelper.Md5(userWai.Password);
            userWai.Password = EncryptHelper.Sha1(userWai.Password);
            UserEntity userEntity = new UserEntity
            {
                Id = Guid.NewGuid().ToString("N").Substring(0,29),
                Username = userWai.Username,
                Password = userWai.Password,
                Uname = userWai.Uname
            };
            _DbContext.user.Add(userEntity);
            _DbContext.SaveChanges();
        }
        public void UpdateUser(UserEntity userEntity)
        {
            _DbContext.user.Update(userEntity);
            _DbContext.SaveChanges();
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userWai"></param>
        public void DeleteUser(string id)
        {
            UserEntity userEntity = new UserEntity { Id = id };
            _DbContext.user.Remove(userEntity);
            _DbContext.SaveChanges();
        }
        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        public List<UserEntity> GetAllUser()
        {
            List<UserEntity> allUserLists = _DbContext.user.ToList();//从数据库获得所有用户
            return allUserLists;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public string Login(String username,String password)
        {
            password = EncryptHelper.Sha1(password);
            //new一个userentity接收前面传来的用户名密码
            UserEntity userEntity = new UserEntity
            {
                Username = username,
                Password = password                
            };
            //数据源
            List<UserEntity> allUserLists = _DbContext.user.ToList();
            List<UserEntity> userresultlist = new List<UserEntity>();
            //创建查询
            var userresult =
                from user in allUserLists
                where user.Username == username //&& user.Password == password
                select user;
            //执行查询
            foreach (UserEntity user in userresult)
            {
                userresultlist.Add(new UserEntity
                {
                    Username = user.Username,
                    Password = user.Password
                });              
            }
            //对比用户名密码是否匹配
            if (userresultlist.Exists(userresultlist=>userresultlist.Password== userEntity.Password))
            {
                string token = _jwt.GetToken();
                
                return token;
            }
            else
            {
                return "";
            }            
        }
        

    }
   
    public static class EncryptHelper
    {
        /// <summary>
        /// 基于Md5的自定义加密字符串方法：输入一个字符串，返回一个由32个字符组成的十六进制的哈希散列（字符串）。
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <returns>加密后的十六进制的哈希散列（字符串）</returns>
        public static string Md5(this string str)
        {
            //将输入字符串转换成字节数组
            var buffer = Encoding.Default.GetBytes(str);
            //接着，创建Md5对象进行散列计算
            var data = MD5.Create().ComputeHash(buffer);

            //创建一个新的Stringbuilder收集字节
            var sb = new StringBuilder();

            //遍历每个字节的散列数据 
            foreach (var t in data)
            {
                //格式每一个十六进制字符串
                sb.Append(t.ToString("X2"));
            }

            //返回十六进制字符串
            return sb.ToString();
        }

        /// <summary>
        /// 基于Sha1的自定义加密字符串方法：输入一个字符串，返回一个由40个字符组成的十六进制的哈希散列（字符串）。
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <returns>加密后的十六进制的哈希散列（字符串）</returns>
        public static string Sha1(this string str)
        {
            var buffer = Encoding.UTF8.GetBytes(str);
            var data = SHA1.Create().ComputeHash(buffer);

            var sb = new StringBuilder();
            foreach (var t in data)
            {
                sb.Append(t.ToString("X2"));
            }

            return sb.ToString();
        }
    }



}

